package com.zhijian.warehouse.manage.util;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;

/**
 * @author HCG
 * @version 1.0
 * @date 2023-09-20
 */
public class ReadJsUtil {

    /**
     * 读取JS文件
     *
     * @param filePath
     * @param methodName
     * @param params
     * @return
     * @throws FileNotFoundException
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public static final String read(String filePath, String methodName, Object... params) {
        // 创建一个ScriptEngineManager对象
        ScriptEngineManager manager = new ScriptEngineManager();

        // 获取JavaScript引擎
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // 加载JavaScript文件
        try {
            engine.eval(new java.io.FileReader(filePath));
        } catch (ScriptException | FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        // 调用JavaScript函数
        Invocable inv = (Invocable) engine;
        try {
            return String.valueOf(inv.invokeFunction(methodName, params));
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static final String exec(String content, String methodName, Object... params) {
        // 创建一个ScriptEngineManager对象
        ScriptEngineManager manager = new ScriptEngineManager();

        // 获取JavaScript引擎
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // 加载JavaScript文件
        try {
            engine.eval(content);
        } catch (ScriptException e) {
            e.printStackTrace();
            return null;
        }

        // 调用JavaScript函数
        Invocable inv = (Invocable) engine;
        try {
            return String.valueOf(inv.invokeFunction(methodName, params));
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        }
    }

}
